import { defineStore } from "pinia";
import {
  fetchSpotcheckList,
  fetchSpotcheckDetail,
  cancelSpotcheck,
  createSpotcheck
} from "../api/verification";

const mapRecord = item => {
  if (!item) return null;
  const snapshot = item.snapshot_product || {};
  return {
    id: item.id,
    verifyNo: item.verify_no,
    status: item.status,
    statusLabel: item.status_label,
    buyerQty: Number(item.buyer_qty ?? 0),
    sellerQty: Number(item.seller_qty ?? 0),
    buyerRemark: item.buyer_remark || "",
    sellerRemark: item.seller_remark || "",
    buyerTime: item.buyer_time,
    sellerTime: item.seller_time,
    auditRemark: item.audit_remark,
    auditTime: item.audit_time,
    snapshot,
    product: {
      id: item.product?.id || item.product_id,
      title: snapshot.title || item.product?.title || "",
      model: snapshot.model || item.product?.model || ""
    },
    media: {
      buyer: item.buyer_media || [],
      seller: item.seller_media || []
    },
    orderId: item.order_id,
    orderNo: item.order_no,
    timeline: {
      created: item.create_time,
      updated: item.update_time
    }
  };
};

export const useVerificationStore = defineStore("buyer-spotcheck", {
  state: () => ({
    records: [],
    total: 0,
    loading: false,
    error: null,
    detailLoading: false,
    detail: null
  }),
  actions: {
    async load(params = {}) {
      this.loading = true;
      this.error = null;
      try {
        const query = {
          page: params.page || 1,
          page_size: params.page_size || 10,
          status: params.status
        };
        const { data } = await fetchSpotcheckList(query);
        const payload = data?.data || data || {};
        const list = payload.list || payload.items || [];
        this.records = list.map(mapRecord).filter(Boolean);
        this.total = payload.total || this.records.length;
      } catch (error) {
        this.error = error.message || "核实记录加载失败";
        throw error;
      } finally {
        this.loading = false;
      }
    },
    async create(cartId, payload = {}) {
      const body = { cart_id: cartId, ...payload };
      const { data } = await createSpotcheck(body);
      const record = mapRecord(data?.data || data || {});
      if (record) {
        this.records = [record, ...this.records];
        this.total += 1;
      }
      return record;
    },
    async loadDetail(id) {
      this.detailLoading = true;
      try {
        const { data } = await fetchSpotcheckDetail(id);
        const payload = data?.data || data || {};
        this.detail = mapRecord(payload);
        return this.detail;
      } finally {
        this.detailLoading = false;
      }
    },
    async cancel(id) {
      await cancelSpotcheck(id);
      this.records = this.records.map(record =>
        record.id === id
          ? { ...record, status: 3, statusLabel: "已取消" }
          : record
      );
      if (this.detail?.id === id) {
        this.detail = { ...this.detail, status: 3, statusLabel: "已取消" };
      }
    },
    clear() {
      this.records = [];
      this.total = 0;
      this.error = null;
      this.detail = null;
    }
  }
});
